﻿using Hangfire;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.MySql.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace DiffuseEnjoyIdle.Extension.Extensions.Hangfire
{
    public static class HangfireExtension
    {
        public static IServiceCollection AddHangfire(this IServiceCollection services, string sqlConn)
        {
            services.AddHangfire(o => o.UseStorage(new MySqlStorage(sqlConn, new MySqlStorageOptions
            {
                TransactionIsolationLevel = System.Data.IsolationLevel.ReadCommitted,// 事务隔离级别。默认是读取已提交。
                QueuePollInterval = TimeSpan.FromSeconds(30),             //- 作业队列轮询间隔。默认值为15秒。
                JobExpirationCheckInterval = TimeSpan.FromHours(1),       //- 作业到期检查间隔（管理过期记录）。默认值为1小时。
                CountersAggregateInterval = TimeSpan.FromMinutes(5),      //- 聚合计数器的间隔。默认为5分钟。
                PrepareSchemaIfNecessary = true,                          //- 如果设置为true，则创建数据库表。默认是true。
                DashboardJobListLimit = 50000,                            //- 仪表板作业列表限制。默认值为50000。
                TransactionTimeout = TimeSpan.FromMilliseconds(10),             //- 交易超时。默认为1分钟。
            })));

            return services;
        }

        public static IApplicationBuilder UseMyHangfireDashboard(this IApplicationBuilder app, string path = "/hangfire", string loginName = "admin", string password = "123456")
        {
            app.UseHangfireDashboard(path, new DashboardOptions
            {
                Authorization = new[]
                {
                    new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                    {
                        SslRedirect = false,          // 是否将所有非SSL请求重定向到SSL URL
                        RequireSsl = false,           // 需要SSL连接才能访问HangFire Dahsboard。强烈建议在使用基本身份验证时使用SSL
                        LoginCaseSensitive = false,   //登录检查是否区分大小写
                        Users = new[]                 //配置登陆账号和密码
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login =loginName,//用户名
                                PasswordClear=password
                            }
                        }
                    })
                }
            });

            return app;
        }
    }
}
